<script setup lang="ts">
import dayjs from 'dayjs'
import type { FormInstance } from 'element-plus'
import CustomDialog from '@/components/CustomDialog/CustomDialog.vue'

import {
  RenderWarningTag,
  renderType,
} from '@/mixins/Warning'

import { alarmApi } from '@/api'

import type { WarningInfo, WorkOrderUser } from '@/types'

const props = defineProps<{
  userLists: WorkOrderUser[]
  warningInfo: WarningInfo
}>()
const emits = defineEmits<{
  (e: 'save-success'): void
}>()
const dialogRef = ref<InstanceType<typeof CustomDialog>>()
const formRef = ref<FormInstance>()

const info: {
  users: WorkOrderUser['userId'][]
  time: string
} = reactive({
  users: [],
  time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
})
const rules = {
  users: [
    { required: true, message: '请选择处理人' },
    {
      validator(_rule: any, value: any, callback: any) {
        if (value.length < 1) {
          callback(new Error('请选择处理人'))
        }
        else {
          callback()
        }
      },
    },
  ],
  time: [
    { required: true, message: '请选择期望处理结束时间' },
  ],
}
const checkedUsers = computed(() => {
  const users = props.userLists
  return users.filter(v => info.users.includes(v.userId))
})

function open() {
  info.users = []
  info.time = dayjs().format('YYYY-MM-DD HH:mm:ss')
  dialogRef.value?.open()
}
function close() {
  dialogRef.value?.close()
}

async function clickSave(done: any) {
  const isValid = await formRef.value
    ?.validate()
    .catch(() => {
      done()
    })
  if (isValid) {
    try {
      await alarmApi.saveWarningWorkOrder({
        warningId: props.warningInfo.id,
        processingEndTime: info.time,
        warningWorkOrderUserList: props.userLists.filter(
          v => info.users.includes(v.userId),
        ),
      })
      done()
      close()
      ElMessage.success('保存成功')
      emits('save-success')
    }
    catch (e) {
      done()
      console.log(e)
    }
  }
}

function clickCloseTag(tag: WorkOrderUser) {
  // console.log(tag);
  info.users = info.users.filter(v => v !== tag.userId)
}

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    title="告警处理指派"
    need-saving
    class="custom-dialog"
    @confirm="clickSave"
  >
    <ElDescriptions title="告警信息" border :column="2">
      <ElDescriptionsItem label="告警类型">
        <RenderWarningTag
          :warning-info="warningInfo"
          :render="renderType"
        />
      </ElDescriptionsItem>
      <ElDescriptionsItem label="告警持续时间">
        {{ warningInfo.warningLastTime }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="指标名称">
        {{ warningInfo.indicatorName }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="测点点位号">
        {{ warningInfo.indicatorCode }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="指标编码" :span="2">
        {{ warningInfo.indicatorNumber }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="设备名称/点位" :span="2">
        {{ warningInfo.pointNameFull }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="告警开始时间" :span="2">
        {{ warningInfo.warningStartTime }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="告警内容" :span="2">
        {{ warningInfo.warningContent }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="阈值下限-上限">
        {{ warningInfo.thresholdValue }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="告警发生值">
        {{ warningInfo.warningValue }}
      </ElDescriptionsItem>
    </ElDescriptions>
    <div
      class="el-descriptions__header"
      style="margin-bottom: 16px; margin-top: 16px"
    >
      <div class="el-descriptions__title">
        处理信息
      </div>
    </div>
    <ElForm
      ref="formRef"
      :model="info"
      :rules="rules"
      label-position="top"
      style="position: relative"
    >
      <ElFormItem
        class="width-50"
        label="选择处理人"
        prop="users"
      >
        <ElSelect
          v-model="info.users"

          clearable filterable collapse-tags multiple
          :multiple-limit="5"
          class="width-100"
        >
          <ElOption
            v-for="item in userLists"
            :key="item.userId"
            :label="`${item.userName}（${item.loginName}）`"
            :value="item.userId"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem
        class="width-50"
        label="期望处理结束时间"
        prop="time"
      >
        <ElDatePicker
          v-model="info.time"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm"
          style="--el-date-editor-width: 100%"
        />
      </ElFormItem>
      <div class="checked-users-wrap">
        <div class="checked-users-label">
          已选处理人
          <small>（{{ checkedUsers.length }}/5）</small>
        </div>
        <div class="checked-users">
          <ElTag
            v-for="item in checkedUsers"
            :key="item.userId"
            closable
            class="checked-user"
            @close="clickCloseTag(item)"
          >
            {{ item.userName }}
          </ElTag>
        </div>
      </div>
    </ElForm>
  </CustomDialog>
</template>

<style scoped>
.expect-time {
  display: flex !important;
}
.expect-time :deep(.el-form-item__label) {
  margin-bottom: 0 !important;
  line-height: 32px !important;
}
.width-50 {
  width: 50%;
}
.checked-users-wrap {
  position: absolute;
  left: 50%;
  top: 0;
  margin-left: 18px;
  width: calc(50% - 18px);
}
.checked-users-label {
  font-size: 14px;
  line-height: 22px;
  margin-bottom: 8px;
}
.checked-users {
  --el-border-color: #dcdfe6;
  box-shadow: 0 0 0 1px
    var(--el-border-color, var(--el-border-color)) inset;
  height: 112px;
  width: 100%;
  border-radius: 4px;
  padding: 12px;
  box-sizing: border-box;
}
.checked-user {
  float: left;
  margin-right: 10px;
  margin-bottom: 10px;
}
.checked-user :deep(.el-tag__content) {
  max-width: 80px;
  text-overflow: ellipsis;
  overflow: hidden;
}
</style>
